home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7227 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  72 lines

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Why Do Return Values Sometimes Have '&' Appended?
  5. Date: Thu, 22 Feb 1996 10:08:18 +0100
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <312C3282.15FB7483@intellektik.informatik.th-darmstadt.de>
  8. References: <4ggciv$iq1@alcor.usc.edu>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. Abu Wawda wrote:
  16. > I have seen code where some of the functions are returned with the
  17. > reference operator (&) attached to the end. Here is an example:
  18. > MyReturn& MyFunction(...)
  19. > {
  20. > }
  21. > I don't understand what that does. I have seen this most often in
  22. > operator overloading such as:
  23. > class MyClass
  24. > {
  25. >   MyClass& operator + (MyClass&);
  26. > }
  27. > I understand why you the function parameter uses the & operator since
  28. > you want to pass the class by reference, but why is it used in the
  29. > return value? Thank you,
  30.  
  31. Maybe the operator returns a reference to the dereferenced 'this'-pointer.
  32. This allows to chain several applications of the operator. For instance
  33. a possible expression would be:
  34.  
  35.                                  MyClass a,b,c;
  36.                                  a+b+c;
  37.  
  38. With the given declaration of 'operator +' 'a', 'b' and 'c' may be changed
  39. in the above example. That doesn't conform to the usual semantics of 'operator +'.
  40. A reasonable example could be a list class with a member-function 'Append':
  41.  
  42.         class List {
  43.             ...
  44.             List& Append(int elem) { ...; return *this; }
  45.             ...
  46.         };
  47.  
  48. Such a declaration makes it possible to abbreviate 
  49.  
  50.                 List l;
  51.                 l.Append(2);
  52.                 l.Append(3);
  53.                 l.Append(5)
  54.  
  55. with
  56.  
  57.                 List l;
  58.                 l.Append(2).Append(3).Append(5);
  59.  
  60. i.e. you can chain the function 'Append'. Because of the returned _reference_ to
  61. the deref. this-pointer the subsequent calls of 'Append' do all affect the object
  62. 'l' and not a copy of it.
  63. For instance the iostream-library uses this technique to allow chained expression.
  64.  
  65.     Enno
  66.